//
//  PrefsV2UnitsViewController.m
//  Fuel Log 4
//
//  Created by Olaf on 22.05.10.
//  Copyright 2010 olafgreck. All rights reserved.
//

#import "GasV2ViewController.h"
#import "FuelLogAppDelegate.h"
#import "DateViewController.h"

#import "DebugOutput.h"

#define addGas_NumberOfRows	7
#define addGas_row_date		0	// dateString
#define addGas_Odometer		1	// odometerString
#define addGas_Volume		2  // volumeString
#define addGas_Consumption	3	// consumptionString
#define addGas_Cost			4	// costString
#define addGas_UnitCost		5	// unitCostString
#define addGas_FullTank		6	// fullTankIndicator

@implementation GasViewController

@synthesize gas;
@synthesize doneButton;  
@synthesize textFieldinCell, textFieldBeingEdited;
@synthesize dateString, odometerString, volumeString;
@synthesize consumptionString, costString, unitCostString, fullTankIndicator;

 
#pragma mark -
#pragma mark TextFields

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"inside textFieldDidBeginEditing");
    self.textFieldBeingEdited = textField;
}	

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
	debug(@"in textFieldShouldEndEditing ");
	return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
	debug(@"in textFieldDidEndEditing , textField.tag: %d", textField.tag);
	
	if (textField.tag == addGas_Odometer)	[self setOdometerString:textField.text];
	if (textField.tag == addGas_Volume)		[self setVolumeString:textField.text];
	if (textField.tag == addGas_Cost	)		[self setCostString:textField.text];
	
	[self updateDpf];
}


 


-(BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range 
replacementString:(NSString*)textEntered {
//	debug(@"in shouldChangeCharactersInRange");
	NSCharacterSet * myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789,."];
	for (int i = 0; i < [textEntered length]; i++) 
	{
		unichar c = [textEntered characterAtIndex:i];
		if (![myCharSet characterIsMember:c]) 	return NO;
	}
	return YES;
}	


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	debug(@"in textFieldShouldReturn, %d",  textField.tag);
	if (textField.tag == addGas_Odometer)	[self setOdometerString:textField.text];
	if (textField.tag == addGas_Volume)		[self setVolumeString:textField.text];
	if (textField.tag == addGas_Cost	)		[self setCostString:textField.text];
	[textField resignFirstResponder];
	[self updateDpf];
	[self updateUnitCost];
	return YES;
}

#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
	[self reallyDelete];
}

- (void)reallyDelete {
	if (gas.pk != -1) {
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate removeGas:gas];
	}
	[self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
- (IBAction)done:(id)sender {  
	debug(@"in done");
	if (self.textFieldBeingEdited != nil) {
        [self textFieldDidEndEditing:textFieldBeingEdited];
        self.textFieldBeingEdited = nil;
    } 
	float distance = [FuelLogAppDelegate scanFloat:self.odometerString];
	float fuel = [FuelLogAppDelegate scanFloat:self.volumeString];
	float cost = [FuelLogAppDelegate scanFloat:self.costString];
	if (distance <= 0) {
		[self showErrorText:@"Odometer must be a positive number."];
		return;
	}
	if (fuel <= 0) {
		[self showErrorText:@"Fuel volume must be a positive number."];
		return;
	}
	if (cost < 0) {
		[self showErrorText:@"Cost must be a positive number."];
		return;
	}
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	Gas *lastPump = [appDelegate findPreviousGasEntry:dateValue odometer:distance];
	if (lastPump && (gas.pk == -1 || gas.pk != lastPump.pk)) {
		if (distance < lastPump.odometer) {
			[self showErrorText:[NSString stringWithFormat:@"Odometer is lower than previous value of %.1f", lastPump.odometer]];
			return;
		} else if ([dateValue compare:lastPump.date] == NSOrderedAscending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *lastDate = [formatter stringFromDate:lastPump.date];			
			[self showErrorText:[NSString stringWithFormat:@"Date is earlier than previous fuel date of %@", lastDate]];
			return;
		}
	}
	Gas *nextPump = [appDelegate findNextGasEntry:dateValue odometer:distance];
	if (nextPump && (gas.pk == -1 || gas.pk != nextPump.pk)) { 
		if (distance > nextPump.odometer) {
			[self showErrorText:[NSString stringWithFormat:@"Odometer is higher than next value of %.1f", lastPump.odometer]];
			return;
		} else if ([dateValue compare:nextPump.date] == NSOrderedDescending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *nextDate = [formatter stringFromDate:nextPump.date];
			[self showErrorText:[NSString stringWithFormat:@"Date is later than next fuel date of %@", nextDate]];
			return;
		}
	}
	[gas setDate:dateValue];
	[gas setOdometer:distance];
	[gas setVolume:fuel];
	[gas setCost:cost];
	[gas setFull:self.fullTankIndicator]; 
	[appDelegate addGasIfNeeded:gas previous:lastPump next:nextPump];
	[gas release];
	[self.navigationController popViewControllerAnimated:YES];
}

-(void)showErrorText:(NSString *)errorText {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test"
													message:errorText
												   delegate:nil
										  cancelButtonTitle:@"OK"
										  otherButtonTitles: nil];
	[alert show];
	[alert release];
}

#pragma mark -
#pragma mark Calculations and stuff
-(void)setBoxes {
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	[self setDateString:[formatter stringFromDate:dateValue]];
	[self setOdometerString:[[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:gas.odometer]]];
	//	[fuelLabel setText:[FuelLogAppDelegate pref].fuelText];
	[self setVolumeString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:gas.volume]]];
	//	[dpfLabel setText:[FuelLogAppDelegate pref].dpfText];
	[self updateDpf];
	[self setCostString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:gas.cost]]];
	[self updateUnitCost];
	[self setFullTankIndicator:gas.full];
	/*	if (gas.pk == -1) {
	 deleteButton.hidden = YES;
	 } else {
	 deleteButton.hidden = NO;
	 }
	 */
}
- (void)setGas:(Gas *)anotherGas {
	[gas release];
	gas = anotherGas;
	[gas retain];
	[self setDateValue:gas.date];
}

- (NSDate *)dateValue {
	return dateValue;
}

- (void)setDateValue:(NSDate *)anotherDate {
	[dateValue release];
	dateValue = anotherDate;
	[dateValue retain];
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	[self setDateString:[formatter stringFromDate:dateValue]];
	[self.tableView reloadData];
}

- (void)updateDpf {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	float odometer = [FuelLogAppDelegate scanFloat:odometerString];
	float fuel = [FuelLogAppDelegate scanFloat:volumeString];
	float dpf = [appDelegate gasEconomy:gas.pk odometer:odometer fuel:fuel];
	int prefUnits = [FuelLogAppDelegate pref].units;
	if (dpf > 0.0 &&  prefUnits == INV_METRIC) {
		dpf = 100.0 / dpf;
	} else if (dpf > 0.0 && prefUnits == NORWAY) {
		dpf = 10.0 / dpf;
	} else if (prefUnits == UK) {
		dpf = dpf * UK_GALLON;
	}
	[self setConsumptionString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:dpf]]];
	[self.tableView reloadData];
}

- (void)updateUnitCost {
	float v = [FuelLogAppDelegate scanFloat:self.volumeString];
	if (v > 0.0) {
		float c = [FuelLogAppDelegate scanFloat:self.costString];
		float uc = c/v;
		NSNumberFormatter *unitCostFormatter = [FuelLogAppDelegate pref].unitCostFormatter;
		[self setUnitCostString:[unitCostFormatter stringFromNumber:[NSNumber numberWithFloat:uc]]];
	} else if ([FuelLogAppDelegate scanFloat:self.unitCostString] != 0.0) {
		[self setUnitCostString:@"0"];
	}
}


#pragma mark -
#pragma mark Init and View

- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
		doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
																   target:self
																   action:@selector(done:)];
		self.navigationItem.rightBarButtonItem = doneButton;
    }
	
 	return self;
}


 

/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to preserve selection between presentations.
 self.clearsSelectionOnViewWillAppear = NO;
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */


- (void)viewWillAppear:(BOOL)animated {
	debug(@"in viewWillAppear");
	[(UIScrollView*)[self view] setScrollEnabled:NO];
	[self.navigationController setToolbarHidden:YES animated:YES];
	[super viewWillAppear:animated];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source
/*
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 //CGFloat hightForRow = (480 - 44) / (float)[primaryLabelStringArray count];
 return 50; //hightForRow;
 }
 // */

/*
 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
 NSString * returnValue = @"";
 FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
 if (appDelegate.currentCar) {
 returnValue = appDelegate.currentCar.label;
 }
 return  returnValue;
 }
 */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	NSInteger returnValue = 0;
	if (gas.pk == -1) returnValue = 1;
	else  returnValue = 2;
    return returnValue;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	NSInteger returnValue = 0;
	if (section == 0 ) returnValue = addGas_NumberOfRows;
	else  returnValue = 1;
    return returnValue;
}


// Customize the appearance of table view cells.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"CellIdentifier";
	//debug(@"section %d, row %d", indexPath.section, indexPath.row);
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
	cell.accessoryType=UITableViewCellAccessoryNone;
	if (indexPath.section == 0) {
		CGRect frame = CGRectMake(140 ,5, 110, 30);
		
		UITextField *textField = [[[UITextField alloc] initWithFrame:frame] autorelease];
		textField.clearsOnBeginEditing = NO;
		textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
		textField.textAlignment = UITextAlignmentRight;
		textField.textColor = [UIColor colorWithRed:0.22 green:0.329 blue:0.529 alpha:1];
		textField.clearButtonMode =	UITextFieldViewModeWhileEditing;
		textField.borderStyle =UITextBorderStyleRoundedRect;
		textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;  
		textField.returnKeyType = UIReturnKeyDone; //   cannot reach next field
		textField.delegate = self;
		textField.tag = indexPath.row; 
		
		switch (indexPath.row) {
			case addGas_row_date: // simple cell used as a button
				cell.textLabel.text = (NSLocalizedString(@"Date", @"Date"));
				cell.detailTextLabel.text = self.dateString;
				break;
			case addGas_Odometer: // will have UITextField
				cell.textLabel.text = (NSLocalizedString(@"Odometer", @"Odometer"));
				textField.text = self.odometerString;
				[cell setAccessoryView:textField];
				break;
			case addGas_Volume:		// will have UITextField
				cell.textLabel.text = (NSLocalizedString(@"Volume", @"Volume"));
				textField.text = self.volumeString;
				[cell setAccessoryView:textField];
				break;
			case addGas_Consumption:
				cell.textLabel.text = [FuelLogAppDelegate pref].dpfText;
				cell.detailTextLabel.text = self.consumptionString;
				break;
			case addGas_UnitCost:
				cell.textLabel.text = (NSLocalizedString(@"Cost", @"Cost"));
				cell.detailTextLabel.text = self.unitCostString;
				break;
			case addGas_Cost:		// will have UITextField
				cell.textLabel.text = (NSLocalizedString(@"Unit Cost", @"Unit Cost"));
				textField.text = self.costString;
				[cell setAccessoryView:textField];
				break;
			case addGas_FullTank:
				cell.textLabel.text = (NSLocalizedString(@"Full Tank", @"Full Tank"));
				UISwitch * stateSwitch = [[[UISwitch alloc]  initWithFrame:CGRectZero] autorelease];
				stateSwitch.on = fullTankIndicator;
				stateSwitch.tag = 0 ;
				[stateSwitch addTarget:self
								action: @selector(actionFlipRowState:)
					  forControlEvents: UIControlEventValueChanged];
				[cell setAccessoryView:stateSwitch]; 
				break;
			default:
				break;
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;

	}
	else {
		cell.textLabel.text = (NSLocalizedString(@"Delete Entry", @"Delete Entry"));
		cell.textLabel.textAlignment = UITextAlignmentCenter; 
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;

	}
	return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	debug(@"selected cell section %d, Row: %d",indexPath.section, indexPath.row);
	if ((indexPath.section == 0) && (indexPath.row == addGas_row_date)) {
		DateViewController *dateController = [[DateViewController alloc] initWithNibName:@"Date" bundle:nil];
		//[FuelLogViewController dateViewController];
		[dateController setEditedObject:self];
		[dateController setEditedFieldKey:@"dateValue"];
		[dateController setText:@"Date"];
		[dateController setDateValue:dateValue];
		[self.navigationController pushViewController:dateController animated:YES];
	}
	if ((indexPath.section == 1) && (indexPath.row == 0)){
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Delete this entry?"
													   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes, Delete", nil];
		[alert show];
		[alert release];
	}
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	[tableView reloadData];
	
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	debug(@"selected cell section %d, Row: %d",indexPath.section, indexPath.row);
}

- (void)actionFlipRowState:(id)sender {
	UISwitch *tempSwitch = (UISwitch *)sender;
	fullTankIndicator = tempSwitch.on;
	debug(@"in actionFlipRowState: %d , %d", fullTankIndicator, tempSwitch.on);
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[gas release]; 
	[dateValue release]; 
	[doneButton release]; 
	[textFieldBeingEdited release];  
	[dateString release];
	[odometerString release];
	[volumeString release];
	[consumptionString release];
	[costString release];
	[unitCostString release];
	
	
    [super dealloc];
}


@end

